package org.ethereum.net.dpos;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;

public class ConfirmedSyncMessage extends DPOSMessage {

	private final String rounds;
	
	private final byte[] candicateId;
	
	private final List<Long> roundList;
	
	public ConfirmedSyncMessage(final byte[] encoded) {
		super(encoded);
		
		RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
		this.rounds = new String(paramsList.get(0).getRLPData());
		this.roundList = new ArrayList<Long>();
		String str = rounds.substring(1, rounds.length() -1);
		String[] roundValues = str.trim().split(",");
		for (String r: roundValues) {
			if (r.trim().length() == 0) {
				continue;
			}
			this.roundList.add(Long.valueOf(r.trim()));
		}
        this.candicateId = paramsList.get(1).getRLPData();
	}
	
	public ConfirmedSyncMessage(final List<Long> rounds, final byte[] candicateIds) {
        super(null);
        if (rounds.size() < 0) {
	    		throw new IllegalArgumentException("confirmed rounds must not be empty!");
	    }
        this.roundList = rounds;
        this.rounds = rounds.toString();
        this.candicateId = candicateIds;
        
        encode();
    }
	
	private void encode() {
		byte[] rounds = RLP.encodeElement(this.rounds.getBytes());
		byte[] candicateIds  = RLP.encodeElement(this.candicateId);
		this.encoded = RLP.encodeList(rounds, candicateIds);
	}
	
	public List<Long> getRounds() {
		return roundList;
	}

	public byte[] getCandicateId() {
		return candicateId;
	}

	@Override
	public DPOSMessageCodes getCommand() {
		return DPOSMessageCodes.CONFIRMED_BLOCK_SYNC;
	}

	@Override
	public byte[] getEncoded() {
		return this.encoded;
	}

	@Override
	public Class<?> getAnswerMessage() {
		return VotePresidentResponse.class;
	}

	@Override
	public String toString() {
		return "{round: " + roundList + ", candicate ids: " + Arrays.toString(candicateId) + " }";
	}

}
